package controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.Blob;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import utils.UtilFuncoes;
import br.com.jf.annotations.ControllerJF;
import br.com.jf.annotations.HttpServletRequestJF;
import br.com.jf.annotations.HttpServletResponseJF;
import br.com.jf.annotations.InjectJF;
import br.com.jf.annotations.MethodJF;
import br.com.jf.annotations.RequestTypeJF;
import br.com.jf.annotations.ScopeTypeJF;
import br.com.jf.constants.RequestType;
import br.com.jf.constants.ScopeType;

@ControllerJF(urlPattern = "imagemUsuario")
@ScopeTypeJF(scope=ScopeType.NONE)
public class CarregarImagemUsuarios {

	@InjectJF
	private ServletContext context;
	
	@InjectJF
	private ServletConfig config;

	
	@MethodJF
	@RequestTypeJF(method=RequestType.GET,name="carregarImagem")
	public void carregarImagem(@HttpServletRequestJF HttpServletRequest request, @HttpServletResponseJF HttpServletResponse response) throws ServletException, IOException, SQLException{
		
		HttpSession sessao = request.getSession(true);
		Blob imagemUsuario = (Blob) sessao.getAttribute(UtilFuncoes.IMAGEM_USUARIO);
		
		byte[] vetorImagem = imagemUsuario.getBytes(1, (int) imagemUsuario.length());
	
		ByteArrayInputStream in = new ByteArrayInputStream(vetorImagem);
		
		ServletOutputStream out = response.getOutputStream();
		
		int tamanho = 0;
		byte[] buffer = new byte[1024];
		
		while((tamanho = in.read(buffer)) != -1){
			out.write(buffer,0,tamanho);
		}
		
		out.flush();
	}
	
}
